#include "ImageList.h"

class ImageList_Cleaner {
public:
    ~ImageList_Cleaner() {
        ImageList::destroy();
    }
} ImageList_cleaner_instance;

ImageList* ImageList::instance = NULL;

ImageList::ImageList()
{
    if(Debug::test(DEBUG_CREATE_DELETE)) {
        cout << "ImageList Created" << endl;
    }
}

ImageList* ImageList::get_instance() {
    if(!instance) {
        instance = new ImageList();
    }
    return instance;
}

void ImageList::destroy() {
    if( instance) {
        delete(instance);
        instance = NULL;
        if(Debug::test(DEBUG_CREATE_DELETE)) {
            cout << "ImageList Destroyed" << endl;
        }
    }
}

bool ImageList::add(uint id, const string &imagePath)
{
    ImageListItem newItem;
    newItem.m_imgId = id;
    newItem.m_pImg = new Image_Wrapper(imagePath);
    newItem.m_id = ID_Manager::get_instance().get_ID();
    if(Debug::test(DEBUG_ADD_REMOVE)) {
        cout << "Going to add new image id = " << id << endl;
    }
    m_mutex.lock();
    m_images.push_back(newItem);
    m_mutex.unlock();
    return true;
}

Image_Wrapper *ImageList::find(uint id)
{
    list<ImageListItem>::iterator i;
    m_mutex.lock();
   for(i=m_images.begin(); i != m_images.end(); ++i) {
       if(i->m_imgId == id) {
           m_mutex.unlock();
           return i->m_pImg;
       }
   }
   m_mutex.unlock();
   return NULL;
}

ImageListItem &ImageList::operator[](uint imgId)
{
    list<ImageListItem>::iterator i;
    m_mutex.lock();
    for(i=m_images.begin(); i != m_images.end(); ++i) {
        if(i->m_imgId == imgId) {
            break;
        }
    }

    if (i == m_images.end()) {

        throw runtime_error("ImageListItem &ImageList::operator[](uint imgId) : Could not find image " + formatInt(imgId,4));
    }

    m_mutex.unlock();
    return *i;
}

SpriteList &ImageList::getSpriteList(uint imgId)
{
    list<ImageListItem>::iterator i;
    m_mutex.lock();
    for(i=m_images.begin(); i != m_images.end(); ++i) {
        if(i->m_imgId == imgId) {
            break;
        }
    }

    if (i == m_images.end()) {
        throw runtime_error("SpriteList &ImageList::getSpriteList(uint imgId) : Could not find image " + formatInt(imgId,4));
    }

    m_mutex.unlock();
    return i->m_spriteList;
}

void ImageList::clear()
{
    list<ImageListItem>::iterator itr;
    for (itr = m_images.begin(); itr != m_images.end(); itr++) {
        itr->m_spriteList.clear();
        delete itr->m_pImg;
        itr->m_pImg = NULL;
    }
    m_images.clear();
}
